//
//  BannerAdCellModel.swift
//  iPhone
//
//  Created by Toj on 5/24/23.
//

import UIKit
import GoogleMobileAds

class BannerAdCellModel: NSObject {
    private var _defaultSize = CGSize.def_cipher
    private var _showSize = CGSize(width: .sr_width, height: 100)
    var _cellSize: CGSize {
        return isShowAd ? _showSize : _defaultSize
    }
    
    var isShowAd: Bool {
        return (isRequest && isSetNeedsLayout && !adUnitID.isEmpty)
    }
    
    private(set) var number = ""
    
    private(set) var adUnitID = ""
    
    // 是否需要更新布局
    var isSetNeedsLayout = false
    var isRequest = false
    
    var _loadedComplete: ((_ cellModel: BannerAdCellModel, _ isSuccess: Bool)->Void)?
    
    init(_ model: BannerAdModel) {
        super.init()
        number = String(model.index)
    }
}

extension BannerAdCellModel {

    func requestAdInfo(complete: @escaping ()->Void) {
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            self.response()
            complete()
        }
    }
    
    func response() {
        isRequest = true
        let count = kBannerAdUnitIDs.count
        let unitIDIndex = Int(arc4random_uniform(UInt32(count)))
        adUnitID = kBannerAdUnitIDs[unitIDIndex]
    }
    
    func loadAd(adView: GADBannerView, complete: ((_ cellModel: BannerAdCellModel, _ isSuccess: Bool)->Void)?) {
        _loadedComplete = complete
        //let _adView = GADBannerView(adSize: size)
        adView.adUnitID = adUnitID
        adView.delegate = self
        adView.rootViewController = UIViewController.vc_currentNavigationTopViewController
        adView.load(GADRequest())
    }
}

extension BannerAdCellModel: GADBannerViewDelegate {

    func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID)")
        isSetNeedsLayout = true
        _loadedComplete?(self, true)
        //delegate.collectionViewInvalidateLayout()
    }

    func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
        let adUnitID = bannerView.adUnitID ?? ""
        print("-->toj: func:\(#function), adUnitID:\(adUnitID), size:\(bannerView.adSize)")
        print("-->toj: func: \(#function) msg: \(error.localizedDescription)")
        isSetNeedsLayout = false
        _loadedComplete?(self, false)
        //delegate.collectionViewInvalidateLayout()
    }

    func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
    }
}

extension BannerAdCellModel: UICollectionViewCellModelProtocol {
    
    /// 注册类
    static var registerCell: UICollectionViewCell.Type {
        return BannerCollectionViewCell.self
    }
    
    var cellSize: CGSize {
        return _cellSize
    }
    
    var willShowCellSize: CGSize {
        return _showSize
    }
}
